<?php

// $Id: manage.php, 2010/08/17 afterlastangel$

/**
 * This page prints a particular instance of diemrenluyen
 *
 * @author  Le Kien Truc <afterlastangel@gmail.com>
 * @version $Id: manage.php, 2010/08/17$
 * @package mod/diemrenluyen
 */
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/locallib.php');


$id = optional_param('id', 0, PARAM_INT); // course_module ID, or
$a = optional_param('a', 0, PARAM_INT);  // diemrenluyen instance ID
//Lay du lieu thang nam cua diem ren luyen, neu khong co dat bang ngay bay gio
$drl_year = optional_param('get_year', 0, PARAM_INT);
$drl_month = optional_param('get_month', 0, PARAM_INT);

if (!$drl_month) {
    $currenttime = time();
    $currentdate = usergetdate($currenttime);
    $drl_month = $currentdate['mon'];
    $drl_year = $currentdate['year'];
}

$group = optional_param('group', -1, PARAM_INT);

if ($id) {
    if (!$cm = get_coursemodule_from_id('diemrenluyen', $id)) {
        error('Course Module ID was incorrect');
    }

    if (!$course = get_record('course', 'id', $cm->course)) {
        error('Course is misconfigured');
    }

    if (!$diemrenluyen = get_record('diemrenluyen', 'id', $cm->instance)) {
        error('Course module is incorrect');
    }
} else if ($a) {
    if (!$diemrenluyen = get_record('diemrenluyen', 'id', $a)) {
        error('Course module is incorrect');
    }
    if (!$course = get_record('course', 'id', $diemrenluyen->course)) {
        error('Course is misconfigured');
    }
    if (!$cm = get_coursemodule_from_instance('diemrenluyen', $diemrenluyen->id, $course->id)) {
        error('Course Module ID was incorrect');
    }
} else {
    error('You must specify a course_module ID or an instance ID');
}

require_login($course, true, $cm);

add_to_log($course->id, "diemrenluyen", "view", "manage.php?id=$cm->id", "$diemrenluyen->id");
if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
    print_error('badcontext');
}
require_capability('mod/diemrenluyen:takemark', $context);

if ($form = data_submitted()) {
    $formarr = (array) $form;
    $i = 0;
    $now = time();
    foreach ($formarr as $key => $value) {

        if (substr($key, 0, 7) == 'confirm' && $value == 'on') {
            $students[$i] = new Object();
            $sid = substr($key, 7);
            $students[$i]->diemrenluyenid = $diemrenluyen->id;
            $students[$i]->userid = $sid;
            $students[$i]->month = mktime(0, 0, 0, $drl_month, 1, $drl_year);
            $students[$i]->d1 = $formarr["marks1_$sid"];
            $students[$i]->d2 = $formarr["marks2_$sid"];
            $students[$i]->d3 = $formarr["marks3_$sid"];
            $students[$i]->d4 = $formarr["marks4_$sid"];
            $students[$i]->d5 = $formarr["marks5_$sid"];
            $students[$i]->takenby = $USER->id;
            $i++;
        }
    }
    foreach ($students as $student) {
        if (validate_diemrenluyen($student)) {
            if ($mark = get_record('diemrenluyen_sinhvien', 'month', mktime(0, 0, 0, $drl_month, 1, $drl_year), 'userid', $student->userid)) {
                $student->id = $mark->id; // this is id of log
                update_record('diemrenluyen_sinhvien', $student);
            } else {
                insert_record('diemrenluyen_sinhvien', $student);
            }
        } else
            $mark_errors[] = $student;
    }

//		add_to_log($course->id, 'attendance', 'updated', 'mod/diemrenluyen/view.php?id='.$id.'', $user->lastname.' '.$user->firstname);
//		redirect('manage.php?id='.$id, get_string('success','diemrenluyen'), 3);
//    	exit();
}

/// Print the page header
$strdiemrenluyens = get_string('modulenameplural', 'diemrenluyen');
$strdiemrenluyen = get_string('modulename', 'diemrenluyen');

$navlinks = array();
$navlinks[] = array('name' => $strdiemrenluyens, 'link' => "index.php?id=$course->id", 'type' => 'activity');
$navlinks[] = array('name' => format_string($diemrenluyen->name), 'link' => '', 'type' => 'activityinstance');

$navigation = build_navigation($navlinks);

print_header_simple(format_string($diemrenluyen->name), '', $navigation, '', '', true,
        update_module_button($cm->id, $course->id, $strdiemrenluyen), navmenu($course, $cm));
show_tabs($cm, $context, 'manage');
/// Print the main part of the page
$groupmode = groups_get_activity_groupmode($cm);
$currentgroup = groups_get_activity_group($cm, true);
$sort = 'lastname';
if ($currentgroup) {

    $students = get_users_by_capability($context, 'moodle/legacy:student', '', "u.$sort ASC", '', '', $currentgroup, '', false);
} else {
    $students = get_users_by_capability($context, 'moodle/legacy:student', '', "u.$sort ASC", '', '', '', '', false);
}


/// Now we need a menu for separategroups as well!
if ($groupmode == VISIBLEGROUPS ||
        ($groupmode && has_capability('moodle/site:accessallgroups', $context))) {
    groups_print_activity_menu($cm, "manage.php?id=$id");
}
if ($i) { //Cho biet co sinh vien duoc cap nhat diem;
    //Neu co loi khi cap nhat diem cua mot sinh vien nao do
    if ($mark_errors) {
        print_box_start();
        echo '<div align="center">';
        echo "<font color=\"red\"><b>";
        foreach ($mark_errors as $mark_error) {
            echo fullname($students[$mark_error->userid]) . " " . get_string("hasnotbeenupdated", "diemrenluyen");
        }
        echo "</b></font>";
        echo '</div>';
        print_box_end();
    } else {
        print_box_start();
        echo '<div align="center">';
        echo "<font color=\"red\"><b>";
        echo get_string("updatesuccessfully", "diemrenluyen");
        echo "</b></font>";
        echo '</div>';
        print_box_end();
    }
}
//In thang, nam can quan ly diem ren luyen
print_box_start();
echo '<div align="center">';
echo "<form method=\"post\" action=\"manage.php?id={$cm->id}\">";
$day = 'testday';
$monnth = 'testmonth';
$year = 'testyear';

print_month_selector("get_month", "get_year", mktime(0, 0, 0, $drl_month, 1, $drl_year), $return);
echo '<input type="submit" name="ok" value="' . get_string('chon', 'diemrenluyen') . "\" />\n";
echo '</form>';
echo '</div>';
print_box_end();
$firstname = get_string('firstname');
$lastname = get_string('lastname');
if ($CFG->fullnamedisplay == 'lastname firstname') { // for better view (dlnsk)
    $fullnamehead = "$lastname / $firstname";
} else {
    $fullnamehead = "$firstname / $lastname";
}
unset($teacher_cache); //Luu cache ten cua nguoi cham, giup giam viec truy xuat database
if ($students) {
    unset($table);
    $table->width = '0%';
    $table->head[] = '#';
    $table->align[] = 'center';
    $table->size[] = '20px';

    $table->head[] = '';
    $table->align[] = '';
    $table->size[] = '1px';

    $table->head[] = $fullnamehead;
    $table->align[] = 'left';
    $table->size[] = '';
    $table->wrap[2] = 'nowrap';
    for ($jj = 1; $jj <= 5; $jj++) {
        $table->head[] = "<a href=\"javascript:void(0);\"
                onmouseover=\"return overlib(' " . get_string("desc$jj", "diemrenluyen") . "',
                AUTOSTATUS, WRAP);\" onmouseout=\"nd();\">" . get_string("dieu$jj", "diemrenluyen") . "</a>";
        $table->align[] = 'center';
        $table->size[] = '20px';
    }
    $table->head[] = get_string("Marked by", "diemrenluyen");
    $table->align[] = 'left';
    $table->size[] = '';

    $table->head[] = get_string("Confirm", "diemrenluyen");
    $table->align[] = 'center';
    $table->size[] = '';


    foreach ($students as $student) {

        $i++;
        $mark = get_record('diemrenluyen_sinhvien', 'month', mktime(0, 0, 0, $drl_month, 1, $drl_year), 'userid', $student->id, 'diemrenluyenid', $diemrenluyen->id);
        $table->data[$student->id][] = (!$mark) ? "<font color=\"red\"><b>$i</b></font>" : $i;
        $table->data[$student->id][] = print_user_picture($student->id, $course->id, $student->picture, 20, true, true); //, $returnstring=false, $link=true, $target='');
        $table->data[$student->id][] = "<a href=\"view.php?id={$cm->id}&student={$student->id}\">" . fullname($student) . "</a>";
        for ($jj = 1; $jj <= 5; $jj++) {
            $drl_mark = "d" . $jj;
            $drl_config = "diemrenluyen_diem" . $jj;
            $table->data[$student->id][] = '<input type="text" name="marks' . $jj . '_' . $student->id . '" size="1" value="' . ($mark ? $mark->$drl_mark : $CFG->$drl_config) . '">';
//              In huong dan cho ca phan noi dung nhap vao. Uncomment de su dung
//               $table->data[$student->id][] ='<input type="text" name="marks'.$jj.'_'.$student->id.'" size="1" value="'.($mark ? $mark->$drl_mark : $CFG->$drl_config).'"'
//               . "onmouseover=\"return overlib(' ". get_string("desc$jj","diemrenluyen") . "',
//                AUTOSTATUS, WRAP);\" onmouseout=\"nd();\">";
        }
//            Kiem tra xem co cache ten cua nguoi cham, khong co thi dua vao cache
        if (!$teacher_cache[$mark->takenby]) {
            if ($teacher = get_record('user', 'id', $mark->takenby)) {
                $teacher_cache[$mark->takenby] = fullname($teacher);
            }
        }
//            Lay ten nguoi cham tu trong cache
        if ($mark->takenby) {
            $table->data[$student->id][] = $teacher_cache[$mark->takenby];
        } else
            $table->data[$student->id][] = "";
            $table->data[$student->id][] = '<input type="checkbox" name="confirm' . $student->id . '" />';
    }
}
echo "<form name=\"chamdiemrenluyen\" method=\"post\" action=\"manage.php?id={$cm->id}\">";
print_table($table);
echo '<input type="hidden" name="id" value="' . $id . '">';
echo '<input type="hidden" name="get_year" value="' . $drl_year . '">';
echo '<input type="hidden" name="get_month" value="' . $drl_month . '">';
echo '<input type="hidden" name="sessionid" value="' . $sessionid . '">';
echo '<center><input type="submit" name="esv" value="' . get_string('save', 'diemrenluyen') . '"></center>';
echo '</form>';
/// Finish the page
print_footer($course);
?>
